<?php

class Users extends Public_Controller
{
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function index()
	{
		$this->template->set_layout('blank')->build('admin/auth/login');
	}
	
	function profile(){
		$data['slug'] = 'main';
		$data['user'] = new User($this->session->userdata('id'));
		if(@$_POST)
		{
			if($_FILES['image']['name'])
			{
				$data['user']->delete_file($user->id,'uploads/users/','avatar');
				$_POST['avatar'] = $data['user']->upload($_FILES['image'],'uploads/users/',140,140);
				$data['user']->thumb('uploads/users/thumbs/',100,100);
				$data['user']->thumb('uploads/users/thumbs50x50/',50,50);
			}
			$data['user']->from_array($_POST);
			$data['user']->save();
			set_notify('success', 'บันทึกข้อมูลเรียบร้อยค่ะ');
			redirect('users/profile');
			
			
		}
		$this->template->build('profile',$data);
	}
	
	public function inc_side()
	{
		if(is_login())
		{
			$data['user'] = new User($this->session->userdata('id'));
			$this->load->view('inc_member',$data);
		}
		else
		{
			$this->load->view('inc_side');
		}
	}
	
	public function login()
	{
		if(login($this->input->post('username'), $this->input->post('password')))
		{
			set_notify('success', 'ยินดีต้อนรับเข้าสู่ระบบค่ะ');
			if(user()->level_id <= 2)
			{
				redirect('users/admin/profiles');
			}
			else
			{
				redirect('home');	
			}
		} 
		else
		{
			set_notify('error', 'อีเมล์หรือรหัสผ่านผิดพลาด');
			redirect('home');
		} 
	}
	
	public function logout()
	{
		logout();
		redirect('home');
	}
	
	function register()
	{
		$data['slug'] = 'main';
		//$this->template->append_metadata(js_datepicker());
		$this->template->build('register',$data);
	}
	
	function signup()
	{
		if($_POST)
		{	
			
			$user = new User();
			$user->from_array($_POST);
			$user->last_login = date('Y-m-d H:i:s');
			$user->save();
			login($_POST['username'], $_POST['password']);
			redirect('home');
		}
	}
	
	function forgot()
	{
		if($_POST)
		{
			
		}
		else
		{
			$data['slug'] = 'main';
			$this->template->build("user_forgot",$data);
		}
	}
	
	function check_email()
	{
		$user = new User();
		$user->get_by_username($_GET['username']);
		echo ($user->username)?"false":"true";
	}
	
	function check_display()
	{
		$user = new User();
		$user->get_by_display($_GET['display']);
		echo ($user->username)?"false":"true";
	}
	
	
	function check_captcha()
	{
		if($this->session->userdata('captcha')==$_GET['captcha'])
		{
			echo "true";
		}
		else
		{
			echo "false";
		}
	}
	
}

?>